package com.doodle.common.utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.List;

public class CustomFolder {
	
	private static final String TABLE_NAME = FolderEntry.SCHEMA.getTableName();
	private static final String WHERE_DIRECTORY = FolderEntry.Columns.DIRECTORY + " = ?";
	
    private static CustomFolder sInstance = null;

	private final SQLiteDatabase mDatabase;

    public static synchronized void createInstance(Context context) {
        if (sInstance == null) {
        	sInstance = new CustomFolder(context);
        }
    }

    public static synchronized CustomFolder getInstance() {
        return sInstance;
    }

	private CustomFolder(Context context) {
		mDatabase = new DatabaseHelper(context).getWritableDatabase();
	}

	public List<FolderEntry> getAllFolders() {
		return FolderEntry.SCHEMA.queryAllObjects(mDatabase, FolderEntry.class);
	}

	public void addFolder(String folder) {
		FolderEntry entry = new FolderEntry();
		entry.directory = folder;
		FolderEntry.SCHEMA.insertOrReplace(mDatabase, entry);
		CustomFolderHelper.notifyFolderAdded(folder);
	}

	public void removeFolder(String folder) {
		mDatabase.delete(TABLE_NAME, WHERE_DIRECTORY, new String[] { folder });
		CustomFolderHelper.notifyFolderRemoved(folder);
	}

	public void removeAllFolder() {
		mDatabase.delete(TABLE_NAME, null, null);
		CustomFolderHelper.notifyFoldersCleared();
	}

	public boolean isFolderAdded(String folder) {
		Cursor cursor = mDatabase.query(TABLE_NAME,
				FolderEntry.SCHEMA.getProjection(), WHERE_DIRECTORY, new String[] { folder }, null, null, null);
		if (cursor == null) {
			return false;
		}
		try {
			return cursor.getCount() > 0;
		} finally {
			cursor.close();
		}
	}

	@Entry.Table("custom_folder")
	public static class FolderEntry extends Entry {

		public static final EntrySchema SCHEMA = new EntrySchema(FolderEntry.class);

		public interface Columns extends Entry.Columns {
			public static final String DIRECTORY = "directory";
		}

		@Column(value = Columns.DIRECTORY, unique = true)
		public String directory;

		@Override
		public String toString() {
			return new StringBuilder().append("directory: ").append(directory).toString();
		}
	}

	private static final class DatabaseHelper extends SQLiteOpenHelper {
		
		public static final String DATABASE_NAME = "custom_folder.db";
		public static final int DATABASE_VERSION = 1;

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			FolderEntry.SCHEMA.createTables(db);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			FolderEntry.SCHEMA.dropTables(db);
			onCreate(db);
		}
	}

}
